import { ref, computed, watch } from "vue";

export default function useCounter(initialCounter) {
  // 1. 带 ref 的单个响应式变量
  const counter = ref(0);
  const addCounter = () => {
    counter.value += 1;
  };
  const resetCounter = () => {
    counter.value = 0;
  };

  // 2. 独立的 computed 属性
  const doubleCounter = computed(() => counter.value * 2);
  // 2.1 利用闭包传参
  const multCounter = computed(() => (n) => counter.value * n);

  // 3. watch 响应式更改
  // 3.1 不用指定要监听的选项，从下面的`counter.value`知道了要监听counter
  watch(() => {
    console.log("counter变了" + counter.value);
  });
  // 3.2 指定监听initialCounter
  watch(initialCounter, (newVal, oldVal) => {
    console.log(`initialCounter change from ${oldVal} to ${newVal}`);
    counter.value = newVal;
  });

  return {
    counter,
    addCounter,
    resetCounter,
    doubleCounter,
    multCounter,
  };
}
